const express = require('express')
const route = express.Router()
const advModel = require('../db/model/advModel')
const path = require('path')
//引入权限校验中间件
const isLoginMiddle = require("../middleware/isLoginMiddle")

//引入fromData格式的解析器
const formidable = require("formidable")




route.put('/updateAdv', isLoginMiddle, async (req, res) => {
// res.send('后端获取数据成功')

  const {
    _id
  } = req.query;

  const form = formidable({
    uploadDir: path.resolve(__dirname, "../upload"),
    keepExtensions: true
  })

  form.parse(req, async (err, params, file) => {
    //从解析的params中拿到前台传递的数据
    const {
      advTitle,
      advType,
      advOrder
    } = params;
    console.log(advTitle);

console.log(file);
    try{
    await advModel.updateOne({_id},{
      $set:{
        advTitle,
        advType,
        advOrder,
        advHref:'/upload/'+file.advPic.newFilename,
        updateTime:new Date().toLocaleString()
      }
    })
    return res.send({
      code: 10000,
      msg: "更新广告成功",
      data: null
    })
    }catch(e){
      console.log('更新广告时出现错误'+e.message);
      return  res.send({
        code: 10000,
        msg: '更新广告时出现错误'+e.message,
        data: null
      })
    }


    // console.log(file.advPic.newFilename);

      // const { _id } = req.query
  // const form = formidable({
  //   uploadDir: path.resolve(__dirname, "../upload"),
  //   keepExtensions: true
  // })

  // form.parse(req, async (err, params, file) => {
  //   //从解析的params中拿到前台传递的数据
  //   const {
  //     advTitle,
  //     advType,
  //     advOrder
  //   } = params;

  //   console.log(advTitle);
  // })
  // console.log(req.query, 'req.query ');
  // //  console.log(req.formData ,'req.formData ');
  // res.send('发送成功')

    //向数据库更新数据
    // try {
    //   await advModel.updateOne({
    //     _id
    //   }, {
    //     $set: {
    //       advTitle,
    //       advType,
    //       advOrder,
    //       advHref: "/upload/" + file.advPic.newFilename,
    //       updateTime: new Date().toLocaleString()
    //     }
    //   })

    //   return res.send({
    //     code: 10000,
    //     msg: "更新广告成功",
    //     data: null
    //   })
    // } catch (e) {
    //   console.log("更新广告数据库操作出现异常" + e.message);
    //   return res.send({
    //     code: 10001,
    //     msg: "更新广告数据库操作出现异常" + e.message,
    //     data: null
    //   })
    // }




  })




})

module.exports = route